from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, 
    QLineEdit, QComboBox, QDateEdit, QFileDialog, QMessageBox,
    QCalendarWidget, QGridLayout
)
from PyQt5.QtCore import Qt, QDate
from PyQt5.QtGui import QFont
from datetime import datetime
from dao.index import LoginSchema
from utils.json import JSONHandler
from components.messageBox import CustomMessageBox

class StudentInfoForm(QWidget):
    """学生信息修改页面"""
    def __init__(self):
        super().__init__()
        self.json = JSONHandler("./config/cache.json")
        self.msg = CustomMessageBox()
        self.scale_factor = 0.8  # 总缩放因子调整为0.64
        self.initUI()
        self.setup_stylesheet()
        self.setMinimumSize(int(800 * self.scale_factor), int(600 * self.scale_factor))
        self.set_initial_values()  # 设置表单初始值

    def initUI(self):
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(
            int(40 * self.scale_factor),
            int(30 * self.scale_factor),
            int(40 * self.scale_factor),
            int(30 * self.scale_factor)
        )
        main_layout.setSpacing(int(30 * self.scale_factor))

        # 标题
        title = QLabel("学生信息修改")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet(f"""
            font-size: {int(24 * self.scale_factor)}px; 
            font-weight: bold; 
            color: #2c3e50;
        """)
        main_layout.addWidget(title)

        # 主内容区域
        content_widget = QWidget()
        content_layout = QHBoxLayout(content_widget)
        content_layout.setContentsMargins(0, 0, 0, 0)
        content_layout.setSpacing(int(40 * self.scale_factor))

        # 右侧表单区域
        form_widget = QWidget()
        form_layout = QGridLayout(form_widget)
        form_layout.setContentsMargins(
            int(20 * self.scale_factor),  # 左边距
            int(20 * self.scale_factor),  # 上边距
            int(20 * self.scale_factor),  # 右边距
            int(20 * self.scale_factor)   # 下边距
        )
        form_layout.setVerticalSpacing(int(15 * self.scale_factor))
        form_layout.setHorizontalSpacing(int(20 * self.scale_factor))

        # 表单字段
        self.fields = {
            "姓名": QLineEdit(),
            "学号": QLineEdit(),
            "性别": QComboBox(),
            "班级": QLineEdit(),
            "入学日期": self.create_modern_calendar(),
            "邮箱": QLineEdit()
        }

        # 配置表单元素
        self.fields["性别"].addItems(["男", "女"])
        self.fields["学号"].setEnabled(False)
        self.fields["入学日期"].setEnabled(False)

        # 添加表单到布局
        row = 0
        base_font_size = int(14 * self.scale_factor)
        for label, widget in self.fields.items():
            form_layout.addWidget(QLabel(f"{label}："), row, 0)
            widget.setStyleSheet(f"font-size: {base_font_size}px;")
            form_layout.addWidget(widget, row, 1)
            row += 1

        # 提交按钮
        submit_btn = QPushButton("提交修改")
        submit_btn.clicked.connect(self.validate_form)
        submit_btn.setCursor(Qt.PointingHandCursor)
        form_layout.addWidget(submit_btn, row, 1, Qt.AlignRight)

        content_layout.addWidget(form_widget)
        main_layout.addWidget(content_widget)

    def set_initial_values(self):
        """设置表单初始值"""
        curstudent = self.get_user()
        # 假设从数据库或缓存中获取初始数据
        initial_data = {
            '姓名': curstudent['name'],
            '学号': curstudent['student_number'],
            '性别': '男' if curstudent['gender'] == 1 else "女",
            '班级': curstudent['class_name'],
            '入学日期': QDate.fromString(
                curstudent["入学日期"] if curstudent["enrollment_date"] else datetime.now().strftime("%Y-%m-%d"),
                "yyyy-MM-dd"
            ),
            '邮箱': curstudent['email'] if curstudent['email'] else "未设置"
        }

        # 填充表单字段
        self.fields["姓名"].setText(initial_data["姓名"])
        self.fields["学号"].setText(initial_data["学号"])
        self.fields["性别"].setCurrentText(initial_data["性别"])
        self.fields["班级"].setText(initial_data["班级"])
        self.fields["入学日期"].setDate(initial_data["入学日期"])
        self.fields["邮箱"].setText(initial_data["邮箱"])

    def get_user(self):
        login_schema = LoginSchema().get_student(user_id=self.json.read()["user_id"])
        return login_schema

    def create_modern_calendar(self):
        """创建现代化日历控件"""
        date_edit = QDateEdit()
        date_edit.setCalendarPopup(True)
        date_edit.setDate(QDate.currentDate())
        
        calendar = QCalendarWidget()
        calendar.setGridVisible(False)
        calendar.setVerticalHeaderFormat(QCalendarWidget.NoVerticalHeader)
        
        # 缩放日历样式
        calendar.setStyleSheet(f"""
            QCalendarWidget {{
                background: white;
                border: 1px solid #e0e0e0;
                border-radius: {int(8 * self.scale_factor)}px;
                padding: {int(10 * self.scale_factor)}px;
            }}
            QCalendarWidget QToolButton {{
                height: {int(30 * self.scale_factor)}px;
                width: {int(30 * self.scale_factor)}px;
                icon-size: {int(16 * self.scale_factor)}px {int(16 * self.scale_factor)}px;
            }}
            QCalendarWidget QSpinBox {{
                width: {int(80 * self.scale_factor)}px;
                font-size: {int(14 * self.scale_factor)}px;
            }}
            QCalendarWidget QAbstractItemView {{
                font-size: {int(14 * self.scale_factor)}px;
            }}
        """)
        
        date_edit.setCalendarWidget(calendar)
        return date_edit

    def validate_form(self):
        """验证表单"""
        missing_fields = []
        for field_name, widget in self.fields.items():
            if isinstance(widget, QLineEdit) and not widget.text().strip():
                if field_name != "学号":
                    missing_fields.append(field_name)
            elif isinstance(widget, QComboBox) and not widget.currentText():
                missing_fields.append(field_name)
            elif isinstance(widget, QDateEdit) and not widget.date().isValid():
                missing_fields.append(field_name)

        if missing_fields:
            self.msg.show_error("请填写以下必填字段：\n" + "\n".join(missing_fields))
        else:
            # 收集并打印所有数据
            data = {}
            for field_name, widget in self.fields.items():
                if isinstance(widget, QLineEdit):
                    value = widget.text().strip()
                elif isinstance(widget, QComboBox):
                    value = widget.currentText()
                elif isinstance(widget, QDateEdit):
                    value = widget.date().toString("yyyy-MM-dd")
                data[field_name] = value
            
            formdata = {
                "name": data["姓名"],
                "gender": 1 if data["性别"] == "男" else 2,
                "email": data["邮箱"]
            }
            
            LoginSchema().update_student(user_id=self.json.read()["user_id"], student=formdata)
            self.msg.show_success("信息已更新")

    def setup_stylesheet(self):
        base_padding = int(10 * self.scale_factor)
        self.setStyleSheet(f"""
            QWidget {{
                background: #f8f9fa;
                font-family: 'Microsoft YaHei';
            }}
            QLineEdit, QComboBox, QDateEdit {{
                border: 2px solid #e0e0e0;
                border-radius: {int(6 * self.scale_factor)}px;
                padding: {base_padding}px;
                min-width: {int(280 * self.scale_factor)}px;
                font-size: {int(14 * self.scale_factor)}px;
            }}
            QPushButton {{
                background: #3498db;
                color: white;
                border: none;
                padding: {int(12 * self.scale_factor)}px {int(30 * self.scale_factor)}px;
                border-radius: {int(6 * self.scale_factor)}px;
                font-size: {int(14 * self.scale_factor)}px;
            }}
            QPushButton:hover {{
                background: #2980b9;
            }}
            QPushButton:disabled {{
                background: #bdc3c7;
                color: #7f8c8d;
            }}
        """)